﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
#if COUNT_DRAW_OPERATIONS
using BrainTechLLC;
using BrainTechLLC.ThreadSafeObjects;
#endif

namespace BrainTechLLC.ImageOperatorsNonAForgeDependent
{
    public static class JpegEncoding
    {
        private static ImageCodecInfo[] _allCodecs;
        public static ImageCodecInfo _jpegCodec;
        public static EncoderParameters _jpegParams;
        private static int _jpegSaveQuality = 100;

        static JpegEncoding()
        {
            SetJPEGConversionQuality(100);
        }

        public static ImageCodecInfo GetJPEGCodec()
        {
            if (_allCodecs == null)
            {
                Interlocked.CompareExchange<ImageCodecInfo[]>(ref _allCodecs, ImageCodecInfo.GetImageEncoders(), null);
            }

            for (int i = 0; i < _allCodecs.Length; i++)
            {
                ImageCodecInfo codec = _allCodecs[i];

                if (codec.MimeType == "image/jpeg")
                {
                    ImageCodecInfo imageInfo = null;
                    Interlocked.Exchange(ref imageInfo, codec);
                    return imageInfo;                    
                }
            }

            return null;
        }

        public static int GetJPEGParamsForConversionQuality(int desiredQuality, out ImageCodecInfo jpegCodec, out EncoderParameters jpegParams)
        {
            jpegCodec = GetJPEGCodec();            
            jpegParams = new EncoderParameters(1);
            jpegParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, desiredQuality);
            return desiredQuality;
        }

        public static int SetJPEGConversionQuality(int desiredQuality)
        {            
            if (desiredQuality == _jpegSaveQuality && _jpegParams != null) 
            {
                return desiredQuality;
            }

            if (_jpegCodec == null)
            {
                _jpegCodec = GetJPEGCodec();
            }
            
            _jpegParams = new EncoderParameters(1);
            _jpegParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, desiredQuality);
            _jpegSaveQuality = desiredQuality;
            return _jpegSaveQuality;
        }
    }
}
